#include "config_network.h"


#define CONFIG_HTML_PAGE \
    "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>北向物联PLC采集模块</title>" \
    "<style>*{box-sizing:border-box;margin:0;padding:0;}body{font-family:'Helvetica Neue',sans-serif;background:#f2f3f5;height:100vh;display:flex;justify-content:center;align-items:center;}" \
    ".card{background:#fff;padding:30px;border-radius:12px;box-shadow:0 2px 12px rgba(0,0,0,0.1);width:320px;}h2{margin-bottom:20px;font-weight:normal;font-size:20px;color:#333;text-align:center;}" \
    "input{width:100%;padding:10px;margin-top:6px;margin-bottom:16px;border:1px solid #dcdfe6;border-radius:4px;font-size:14px;transition:border-color .2s;}" \
    "input:focus{border-color:#409eff;outline:none;}input[type=\"submit\"]{background-color:#409eff;color:white;border:none;font-size:15px;cursor:pointer;transition:background-color .2s;}" \
    "input[type=\"submit\"]:hover{background-color:#66b1ff;}</style></head><body><div class=\"card\">" \
    "<h2>设备网络配置</h2><form action=\"/submit\" method=\"POST\">" \
    "<label>WiFi SSID</label><input type=\"text\" name=\"ssid\" required>" \
    "<label>WiFi 密码</label><input type=\"password\" name=\"password\">" \
    "<input type=\"submit\" value=\"保存并重启\"></form></div></body></html>"


#define AP_CONFIG_ESP_WIFI_SSID      "beixiang"
#define AP_CONFIG_ESP_WIFI_PASS      ""
#define AP_CONFIG_ESP_WIFI_CHANNEL   6
#define AP_CONFIG_MAX_STA_CONN       4


#define TAG "DeviceConfig"

static DeviceConfig manager;

/**
 * 长按boot进入配网模式
 */
void monitor_config_button_task(void *arg) {
	const TickType_t delay = pdMS_TO_TICKS(100);
	const TickType_t long_press_threshold = pdMS_TO_TICKS(3000); // 3秒长按
    gpio_num_t button_pin = (gpio_num_t)arg;
	TickType_t press_start = 0;
	bool button_was_pressed = false;
	bool already_triggered = false;

	while (1) {
		bool pressed = gpio_get_level(button_pin) == 0;

		if (pressed) {
			if (!button_was_pressed) {
				// 刚按下，记录起始时间
				press_start = xTaskGetTickCount();
				button_was_pressed = true;
			} else {
				// 一直按着，检查是否超过时间
				if (!already_triggered && (xTaskGetTickCount() - press_start >=
										   long_press_threshold)) {

					ESP_LOGI(TAG,
							 "Long press detected, restarting for config mode");
					already_triggered = true;
					esp_restart(); // 重启设备进入配网
				}
			}
		} else {
			// 按钮松开，状态重置
			button_was_pressed = false;
			already_triggered = false;
		}

		vTaskDelay(delay);
	}
}



static esp_err_t submit_post_handler(httpd_req_t *req) {
    char content[256] = {0};
    httpd_req_recv(req, content, req->content_len);
    sscanf(content, "ssid=%63[^&]&password=%63[^&]",
           manager.wifi_ssid, manager.wifi_pass);

    nvs_handle_t nvs;
    if (nvs_open("storage", NVS_READWRITE, &nvs) == ESP_OK) {
        nvs_set_str(nvs, "ssid", manager.wifi_ssid);
        nvs_set_str(nvs, "pass", manager.wifi_pass);
        nvs_commit(nvs);
        nvs_close(nvs);
    }

    httpd_resp_set_type(req, "text/plain");
    httpd_resp_sendstr(req, "Config saved. Rebooting...");
    vTaskDelay(pdMS_TO_TICKS(1000));
    esp_restart();
    return ESP_OK;
}

static esp_err_t config_get_handler(httpd_req_t *req) {
    httpd_resp_set_type(req, "text/html");
    httpd_resp_send(req, CONFIG_HTML_PAGE, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

void launch_wifi_ap_with_web_config(void) {
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());  // 清除NVS并重新初始化
        ESP_ERROR_CHECK(nvs_flash_init());
    }

    ESP_ERROR_CHECK(esp_netif_init());
    esp_netif_create_default_wifi_ap();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
        ESP_EVENT_ANY_ID,
        &wifi_event_handler,
        NULL,
        NULL));

    wifi_config_t ap_config = {
        .ap = {
            .ssid = AP_CONFIG_ESP_WIFI_SSID,
            .ssid_len = strlen(AP_CONFIG_ESP_WIFI_SSID),
            .password = AP_CONFIG_ESP_WIFI_PASS,
            .authmode = WIFI_AUTH_WPA_WPA2_PSK,
            .max_connection = AP_CONFIG_MAX_STA_CONN,
            .channel = AP_CONFIG_ESP_WIFI_CHANNEL
        }
    };
    if (strlen(AP_CONFIG_ESP_WIFI_PASS) == 0) {
        ap_config.ap.authmode = WIFI_AUTH_OPEN;
    }
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP,&ap_config));
    ESP_ERROR_CHECK(esp_wifi_start());
    ESP_LOGI(TAG, "wifi_init_softap finished. SSID:%s password:%s channel:%d",AP_CONFIG_ESP_WIFI_SSID,AP_CONFIG_ESP_WIFI_PASS,AP_CONFIG_ESP_WIFI_CHANNEL);

    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    httpd_start(&manager.server, &config);

    httpd_uri_t uri_get = {
        .uri = "/",
        .method = HTTP_GET,
        .handler = config_get_handler
    };

    httpd_uri_t uri_post = {
        .uri = "/submit",
        .method = HTTP_POST,
        .handler = submit_post_handler
    };

    httpd_register_uri_handler(manager.server, &uri_get);
    httpd_register_uri_handler(manager.server, &uri_post);
}

